# encoding: utf-8

class ItemsController < ApplicationController
  before_filter :find_item, :only => [:show, :edit, :update, :destroy, :edit_title]
  
  def index
    @items = Item.valid.filter(params).paginate :page => params[:page], :per_page => 30
  end

  def show
    @item = Item.find(params[:id])
  end

  def new
    @item = Item.new
  end

  def edit
  end

  def create
    @item = Item.new(params[:item])

    if @item.save
      flash[:notice] = 'Item was successfully created.'
      redirect_to(items_url)
    else
      render "new"
    end
  end

  def update
    @item = Item.find(params[:id])

    if @item.update_attributes(params[:item])
      flash[:notice] = 'Item was successfully updated.'
      redirect_to(items_url)
    else
      render "edit"
    end
  end

  def destroy
    @item.del
    
    redirect_to(items_url)
  end
  
  def update_status
    if params[:ids].blank? or params[:ids].all?{|id| id.blank? }
      flash[:error] = "操作失败."
    else
      status = params[:status].blank? ? 0 : params[:status].to_i
      Item.update_all("status = #{status}", "id IN (#{params[:ids].join(',')})")
      flash[:notice] = "操作成功."
    end
    redirect_to items_url
  end
  
  def update_flag
    if params[:ids].blank? or params[:ids].all?{|id| id.blank? }
      flash[:error] = "操作失败."
    else
      flag = params[:flag].blank? ? 0 : params[:flag].to_i
      Item.update_all("flag = #{flag}", "id IN (#{params[:ids].join(',')})")
      flash[:notice] = "操作成功."
    end
    redirect_to items_url
  end
  
  # just send ajax
  def edit_title
    @item.update_attributes!(:name => params[:name]) if request.post?
    
    respond_to do |format|
      format.js { render :layout => false }
      format.json { render :text => @item.to_json }
      format.html { redirect_to items_url }
    end
  end
  
  private

  def find_item
    @item = Item.find(params[:id])
  end
end
